package contacts

// 部门接口
import (
	"encoding/json"
	"errors"
	"fmt"

	"gitee.com/littletow/qywx/services/commons"
)

const (
	GetDepartmentListURL = "https://qyapi.weixin.qq.com/cgi-bin/department/list"
	CreateDepartmentURL  = "https://qyapi.weixin.qq.com/cgi-bin/department/create"
	UpdateDepartmentURL  = "https://qyapi.weixin.qq.com/cgi-bin/department/update"
	DeleteDepartmentURL  = "https://qyapi.weixin.qq.com/cgi-bin/department/delete"
)

// Department 部门结构
type Department struct {
	ID       int    `json:"id" `
	Name     string `json:"name"`
	NameEN   string `json:"name_en"`
	ParentID int    `json:"parentid"`
	Order    int    `json:"order"`
}

// GetDepartmentListResp 部门列表响应
type GetDepartmentListResp struct {
	commons.CommonError
	Departments []Department `json:"department"`
}

// CreateDepartmentReq 创建部门请求参数
type CreateDepartmentReq struct {
	ID       int    `json:"id,omitempty" `
	Name     string `json:"name"`
	NameEN   string `json:"name_en,omitempty"`
	ParentID int    `json:"parentid"`
	Order    int    `json:"order,omitempty"`
}

// CreateDepartmentResp 创建部门响应
type CreateDepartmentResp struct {
	commons.CommonError
	ID int `json:"id"` // 返回部件创建的ID
}

// UpdateDepartmentReq 更新部门请求参数
type UpdateDepartmentReq struct {
	ID       int    `json:"id" `
	Name     string `json:"name,omitempty"`
	NameEN   string `json:"name_en,omitempty"`
	ParentID int    `json:"parentid,omitempty"`
	Order    int    `json:"order,omitempty"`
}

// GetDepartmentList 获取部门列表
// 参考https://open.work.weixin.qq.com/api/doc/90000/90135/90208
func (manager *ContactManager) GetDepartmentList(deparmentid int) (*GetDepartmentListResp, error) {
	token, err := manager.getToken()
	if err != nil {
		return nil, err
	}

	if deparmentid < 1 {
		deparmentid = 1
	}
	url := fmt.Sprintf("%s?access_token=%s&id=%d", GetDepartmentListURL, token, deparmentid)

	var body []byte
	body, err = commons.HTTPGet(url)
	if err != nil {
		return nil, err
	}
	var resp GetDepartmentListResp
	err = json.Unmarshal(body, &resp)
	if err != nil {
		return nil, err
	}
	// 出错返回码，为0表示成功，非0表示调用失败
	if resp.ErrCode != 0 {
		err = fmt.Errorf("GetDepartmentList error : errcode=%v , errormsg=%v", resp.ErrCode, resp.ErrMsg)
		return nil, err
	}
	return &resp, nil

}

// CreateDepartment 创建部门
// 参考https://open.work.weixin.qq.com/api/doc/90000/90135/90205
func (manager *ContactManager) CreateDepartment(department CreateDepartmentReq) (*CreateDepartmentResp, error) {
	token, err := manager.getToken()
	if err != nil {
		return nil, err
	}
	url := fmt.Sprintf("%s?access_token=%s", CreateDepartmentURL, token)

	// 检查必填项
	if department.Name == "" || department.ParentID < 1 {
		return nil, errors.New(commons.ErrParamInValid)
	}
	// 构造Body
	var body []byte
	body, err = commons.PostJSON(url, department)
	if err != nil {
		return nil, err
	}
	var resp CreateDepartmentResp
	err = json.Unmarshal(body, &resp)
	if err != nil {
		return nil, err
	}
	// 出错返回码，为0表示成功，非0表示调用失败
	if resp.ErrCode != 0 {
		err = fmt.Errorf("CreateDepartment error : errcode=%v , errormsg=%v", resp.ErrCode, resp.ErrMsg)
		return nil, err
	}
	return &resp, nil
}

// UpdateDepartment 更新部门
// 参考https://open.work.weixin.qq.com/api/doc/90000/90135/90206
func (manager *ContactManager) UpdateDepartment(department UpdateDepartmentReq) (*commons.CommonError, error) {
	token, err := manager.getToken()
	if err != nil {
		return nil, err
	}
	url := fmt.Sprintf("%s?access_token=%s", UpdateDepartmentURL, token)
	// 检查必填项
	if department.ID < 1 {
		return nil, errors.New(commons.ErrParamInValid)
	}

	// 构造Body
	var body []byte
	body, err = commons.PostJSON(url, department)
	if err != nil {
		return nil, err
	}
	var resp commons.CommonError
	err = json.Unmarshal(body, &resp)
	if err != nil {
		return nil, err
	}
	// 出错返回码，为0表示成功，非0表示调用失败
	if resp.ErrCode != 0 {
		err = fmt.Errorf("UpdateDepartment error : errcode=%v , errormsg=%v", resp.ErrCode, resp.ErrMsg)
		return nil, err
	}
	return &resp, nil
}

// DeleteDepartment 删除部门，注意，（不能删除根部门，不能删除含有子部门、成员的部门）
// 参考 https://open.work.weixin.qq.com/api/doc/90000/90135/90207
func (manager *ContactManager) DeleteDepartment(departmentID int) (*commons.CommonError, error) {
	token, err := manager.getToken()
	if err != nil {
		return nil, err
	}
	// 检查必填项
	if departmentID <= 1 {
		return nil, errors.New(commons.ErrParamInValid)
	}

	url := fmt.Sprintf("%s?access_token=%s&id=%d", DeleteDepartmentURL, token, departmentID)

	// 构造Body
	var body []byte
	body, err = commons.HTTPGet(url)
	if err != nil {
		return nil, err
	}
	var resp commons.CommonError
	err = json.Unmarshal(body, &resp)
	if err != nil {
		return nil, err
	}
	// 出错返回码，为0表示成功，非0表示调用失败
	if resp.ErrCode != 0 {
		err = fmt.Errorf("DeleteDepartment error : errcode=%v , errormsg=%v", resp.ErrCode, resp.ErrMsg)
		return nil, err
	}
	return &resp, nil
}
